<?php

namespace app\api\controller\ec;

use app\common\controller\Api;
use app\common\exception\UploadException;
use think\Config;
use think\Hook;

/**
 * 公共接口
 * 第一步:先添加客户 到ec
 * 第二步:根据客户手机号 获取CrmId
 * 第三步：根据CrmId 获取客户信息
 */
class Eckehu extends Ecbase {

    public function _initialize() {
        parent::_initialize();
    }
    
    /**
     * 废弃客户入库  
     */
    public function tuisongFeiqiKehu(){
        
        
        $controller = '\app\common\controller\zhongzhuan\Autoassigncd';
        $param = ['limit'=>1];
        $data = call_user_func_array(array($controller, 'startAssign'),array($param));
            
            
        
    }



    /**
     * A B类客户入库
     */
    public function assignKehu(){
       
        
        $timestamp = strtotime("today");
        $list = db('ec_assign_kehu')->where('createtime','>',$timestamp)->where('status','<>',2)->order('createtime desc')->limit(1)->select();


        foreach ($list as $key=>$value){

            if(empty($value['auto_assign']))                continue;
            //$status 0 暂停   1 分配中  2 分配完成
            $assing_kehu_detail = db('ec_assign_kehu_detail')->field('SUM(people - success_people) daifenpei,user_id')->where('assign_id',$value['id'])->where('assign_status',1)->select();

            $kehu_list = array();
            $daifenpei = 0;
            foreach ($assing_kehu_detail as $k =>$v){
                if(empty($v['daifenpei']))                    continue;
                $daifenpei = $v['daifenpei'] + $daifenpei;
            }
            if(empty($daifenpei)) continue;

            $limit = $daifenpei > 500 ? 500 :$daifenpei;

            $kehu_list= db('ec_ai_task_phone')->field('id byid,callJobId,customerTelephone,customerName,callInstanceId,yixiang_txt,yixiang_value,startTime')->where([
                'yixiang_value'=>['in',['A','B']],
                'createtime'=>['>',$timestamp],
                'status'=>0
            ])->limit($limit)->order('startTime desc')->select();



            foreach ($kehu_list as $kehu_info){                    
                $controller = '\app\common\controller\zhongzhuan\Autoassign';
                $param = ['assign_id'=>$value['id'],'kehu_info'=>$kehu_info];
                $data = call_user_func_array(array($controller, 'startAssign'),array($param));    
                
                usleep(1000000);
            }

        }
        
               
    }

    
    /** 
     * 推送客户 
     */
    public function addCustomer(){

        $where = ['status'=>['<>',1]];
        $request_data = $this->request->param();
        if(!empty($request_data['ids'])){
            $where['id'] = $request_data['ids'];
        }
        
        $list = db('ec_aiuser_to_ecuser')->where($where)->select();
        
        if(empty($list))$this->error ('没有数据');
        if(count($list) > 1)$this->error ('操作失败');
        $end_list = [];
        foreach ($list as $value){
            $content = json_decode($value['content'],true);
            $end_list[] = $content;
        }
//        $str = '{"followUserId":"20704409","mobile":"15239022234","name":"未命名19647","fields":{"82705932":"F级(无效客户)","82720068":"http:\/\/kaogu.ys681.cn\/20240807KAD3X98528034613_15239022234_early_media.mp3"}}';
//        $end_list = [
//            json_decode($str,true),
//        ];
        $param = [
            'kehu_list' => $end_list,
            'opt_userid'=>$this->optUserId,
        ] ;

        $controller = '\app\common\controller\zhongzhuan\Fenpei';
        $data = call_user_func_array(array($controller, 'addCustomer'), array($param));
        
        $this->success('操作成功',$data);

        
        
        
        
    }
    
    
    /**
     * 更新客户标签  while
     */
    public function ownUpdateKehuLabel(){
        
        $where = ['label_laiyuan_biaoji_status'=>0];
        $request_data = $this->request->param();
        if(!empty($request_data['ids'])){
            $where['id'] = $request_data['ids'];
        }
        
        $yixiang_label_config = [
            'A'=>'84726558','B'=>'84736557','C'=>'84734554','D'=>'84732560','E'=>'84728556','F'=>'84732561'
        ];

        $label_config = [
            '84731318', //客户来源 【新增百应】
        ];

        $list = db('ec_aiuser_to_ecuser')->where($where)->select();

        if(empty($list)){$this->error('没有数据');}
        
        if(count($list) > 1)$this->error ('操作失败');


        $end_list = [];
        foreach ($list as $value){
            $end_list[$value['yixiang_value']][] = $value;
        }
       
        $msg = '成功';
        foreach ($end_list as  $key=>$value){
            
            $break_foreach = false;
            $item_kehu_ids = $crmIds = [] ;
            foreach ($value as $k=>$v){
                
                if(empty($v['crmId'])){
                    $crmId = db('ec_kehu')->where('mobile',$v['mobile'])->value('crmId');
                    if(!empty($crmId)){
                        db('ec_aiuser_to_ecuser')->where('id',$v['id'])->setField('crmId',$crmId);
                    }
                }else{
                    $crmId = $v['crmId'];
                }
                
                //3005 接收人公海范围内有重复客户。
                if(($v['status'] == 0) || ($v['status'] == 2 && !in_array($v['status_code'], [3005])) ){
                    $break_foreach = true;
                    $msg = '请先推送客户';
                    break;
                }
                
                if(empty($v['ecid'])){
                    $break_foreach = true;
                    $msg = '公海客户暂不标记';
                    break;
                }
                
                
                
                if(empty($crmId)){
                    $break_foreach = true;
                    break;
                }
                
                
                
                $crmIds[] = $crmId;
                $item_kehu_ids[] = $v['id'];
            }
            if($break_foreach)break;

            $tmp_label = $label_config;
            $tmp_label[] = $yixiang_label_config[$key];            
            $param = ['crmIds' => implode(',', $crmIds),'optUserId'=>$this->optUserId,'labels'=>implode(',', $tmp_label)] ;         
            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $item_response = call_user_func_array(array($controller, 'updateKehuLabel'), array($param));

            if($item_response['code'] == 200){
                db('ec_aiuser_to_ecuser')->where('id','in',$item_kehu_ids)->setField('label_laiyuan_biaoji_status',1);
            }else{
                $msg = '标记失败';
            }
            
        }
        
        $this->success ($msg);
        
    }
    
    public function batchGetKehuList(){
        
        
        $field_id_config = config('zhongzhuan.field');
        $yixiang_field_id = $field_id_config['yixiang']['fieldid'];
        $baiying_luyin_field_id = $field_id_config['baiying_luyin']['fieldid'];
        
        $currentPage = 1;
              
        
        
        while (true){
            $controller = '\app\common\controller\zhongzhuan\Fenpei';            
                        
            $item_param = ['pageNo'=>$currentPage,'pageSize'=>200,'createUserIdList'=>[$this->optUserId]];
            $response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($item_param));         
            
            if($response['code'] == 200){
                foreach ($response['data']['list'] as $key => $value){
                    
                    $yixiang_txt = $baiying_luyin = '';
                    
                    foreach ($value['fieldInfos'] as $k =>$v){
                        foreach ($v as $item_k =>$item_v){
                            if($item_k == $yixiang_field_id){
                                $yixiang_txt = $item_v;
                            }else if($item_k == $baiying_luyin_field_id){
                                $baiying_luyin = $item_v;
                            }
                        }

                    }
                                     
                    
                    
                    $exist_ = db('ec_kehu')->where('crmId',$value['crmId'])->count();
                    if(!empty($exist_)){
                        db('ec_kehu')->where('crmId',$value['crmId'])->update([       
                            'addtime'=> strtotime($value['createTime']),
                            'name'=> $value['name'],
//                            'follow_userid'=>$value['followUserId'],
                            'yixiang_txt'=>$yixiang_txt,
                            'record_file'=>$baiying_luyin,
                            'luyin_md5'=> md5($baiying_luyin),
                            'content'=> json_encode($value,JSON_UNESCAPED_UNICODE),
                        ]);
                    }else{
                        $insert_data[] = [
                            'crmId'=>$value['crmId'],
                            'mobile'=>$value['mobiles'][0],
                            'name'=> $value['name'],
                            'follow_userid'=>$value['followUserId'],
                            'yixiang_txt'=>$yixiang_txt,
                            'record_file'=>$baiying_luyin,
                            'luyin_md5'=> md5($baiying_luyin),
                            'addtime'=>strtotime($value['createTime']),
                            'follow_userid'=>$value['followUserId'],
                            'content'=> json_encode($value,JSON_UNESCAPED_UNICODE),
                            'createtime'=>time(),
                        ];
                    }
                }
                if(!empty($insert_data)){
                    db('ec_kehu')->insertAll($insert_data);
                }
                
                
                $currentPage = $response['data']['page']['pageNo'] + 1;
                if($currentPage > $response['data']['page']['maxPageNo']){
                    $msg = '成功';
                    break;
                }
            }else{
                $msg = '失败';
                break;
            }
        }
        
        
        
        
        $this->success('成功',$response);
    }
    
    
    
    public function batchGetKeHhCrmByMobile(){
//         $list = db('ec_aiuser_to_ecuser')->where(['status'=>1])->where('crmId','')->select();
         $list = db('ec_aiuser_to_ecuser')->select();
         $mobile = [];
         foreach ($list as $key=>$value){
             $mobile[] = $value['mobile'];
         }
         
        $param = ['mobile' => implode(',', $mobile)] ;
        $controller = '\app\common\controller\zhongzhuan\Fenpei';
        $item_response = call_user_func_array(array($controller, 'getKehuInfoByMobile'), array($param));
        if($item_response['code'] == 200){
            foreach ($item_response['data'] as $value){
                $item_mobile = $value['mobile'];
                foreach ($value['list'] as $k => $v){
                    $item_crmId = $v['crmId'];
                    break;
                }
                
                db('ec_aiuser_to_ecuser')->where(['status'=>1,'crmId'=>'','mobile'=>$item_mobile])->setField('crmId',$item_crmId);
            }
        }
    }
    
    
    
    /**
     * 批量变更跟进人
     */
    public function ownUpdateKehuOwner(){
        
        $list = db('ec_aiuser_to_ecuser')->where(['status'=>2,'ecid'=>['>',0]])->where('id',7)->limit(1)->select();

        foreach ($list as $key=>$value){
            $item_crmId = $value['crmId'];
            $item_mobile = $value['mobile'];
            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $msg_prefix = '[变更跟进人]';

            $save_data = [];
            if(empty($item_crmId)){
                $item_crmId = db('ec_kehu')->where(['mobile'=>$item_mobile])->whereNotNull('crmId')->order('id desc')->value('crmId');                    
            }
            

            if(empty($item_crmId)){
                $param = ['mobile' => $item_mobile] ;
                $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));
                if($item_response['code'] == 200){
                    $item_data = $item_response['data']['list'][0];
                    $item_crmId = $item_data['crmId'];
                }
            }

            if(empty($item_crmId)){
                $save_data['tuisong_result_txt'] = $msg_prefix .  'CrmID不存在';
            }else{
                $save_data['crmId'] = $item_crmId;
                $content = json_decode($value['content'],true);
                if(!empty($content['followUserId'])){
                    $param_owner = ['followUserId'=>$content['followUserId'],'crmIds'=>$item_crmId,'optUserId'=>$this->optUserId];
                    $item_update_owner = call_user_func_array(array($controller, 'updateKehuOwnwer'), array($param_owner));

                    if($item_update_owner['code'] == 200){
                        foreach ($item_update_owner['data']['list'] as $k=>$v){
                            if($v['code'] == 40003 || $v['code'] == 200){
                                $save_data['status'] = 1;
                            }
                            $save_data['tuisong_result_txt'] = $msg_prefix . $v['msg'];
                        }

                    }else{
                        $save_data['tuisong_result_txt'] = $msg_prefix . '请求失败';
                    }
                }else{
                    $save_data['tuisong_result_txt'] = $msg_prefix . '跟进人为空';
                }
                
                
            }      


            db('ec_aiuser_to_ecuser')->where('id',$value['id'])->update($save_data);

        }
        
    }

    

    public function ownUpdateKehuInfo(){
        $kehu_list = db('ec_kehu')->order('updatetime asc')->limit(40)->select();
        
        $luyin_domain_prefix = config('zhongzhuan.luyin_domain_prefix'); 

        $field_id_config = config('zhongzhuan.field');
        $yixiang_field_id = $field_id_config['yixiang']['fieldid'];
        $baiying_luyin_field_id = $field_id_config['baiying_luyin']['fieldid'];
        $update_kehu = [];
        $list = [];
        foreach ($kehu_list as $value){
            $org_info = json_decode($value['content'],true);

            if(empty($org_info))continue;

            $by_kehu_info = db('ec_ai_task_phone')->field('customerTelephone,callInstanceId')->where('customerTelephone',$value['mobile'])->order('id desc')->find();

            if(empty($by_kehu_info))             {

                continue;
            }   

            $new_luyin_file = $luyin_domain_prefix .'?callInstanceId=' .$by_kehu_info['callInstanceId'];     
            if($value['luyin_md5'] == md5($new_luyin_file)){
                echo $value['mobile'] . "\r\n";
                continue;
            }
          

            $fields =[];

            foreach ($org_info['fieldInfos'] as $k =>$v){
                $field_keys = array_keys($v);
                foreach ($field_keys as $item_k){                                           
                    if($item_k == $baiying_luyin_field_id){  //百应录音                            
                        $fields[$item_k] = $luyin_domain_prefix .'?callInstanceId=' .$by_kehu_info['callInstanceId'];                            
                    }else{ //意向度
                        $fields[$item_k] = empty($v[$item_k])?'':$v[$item_k];
                    }

                }

            }

            $update_kehu[$value['crmId']] = ['luyin_md5'=>md5($new_luyin_file),'record_file'=>$new_luyin_file];

            $list[] = [
                "crmId"=>$value['crmId'],"optUserId"=>$this->optUserId,"name"=>$org_info['name'],"fields"=>$fields,
                 "mobile"=>$value['mobile']
            ];


        }       
        
        if(!empty($list)){
            echo date('Y-m-d H:i:s');
            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $response_data = call_user_func_array(array($controller, 'updateInfo'), array(['list'=>$list]));
            if($response_data['code'] == 200){
                foreach ($response_data['data']['successList'] as $value){
                    if(array_key_exists($value, $update_kehu)){
                        $temp = $update_kehu[$value];
                        $temp['updatetime'] = time();
                        db('ec_kehu')->where("crmId",$value)->update($temp);
                    }
                }
            }
        }

        
        
        $this->success('',$response_data);
    }
    
    
    
    
    
    public function setCrmId(){
        $list = db('ec_aiuser_to_ecuser')->where(['status'=>1])->where('crmId','')->select();
        foreach ($list as $key=>$value){
            $crmId  = db('ec_kehu')->where('mobile',$value['mobile'])->value('crmId');
            if(!empty($crmId)){
                db('ec_aiuser_to_ecuser')->where('id',$value['id'])->setField('crmId',$crmId);
            }
        }
    }
    
  
}
